/**<p>项目名：</p>
 * <p>包名：	com.hengxin.module.contract.service.impl</p>
 * <p>文件名：ContractProductServiceImpl.java</p>
 * <p>版本信息：</p>
 * <p>日期：2014-11-4-下午9:41:19</p>
 * Copyright (c) 2014singno.bob公司-版权所有
 */
package com.hengxin.module.contract.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.singno.bob.exception.BusinessException;
import cn.singno.bob.jpa.base.impl.BaseServiceImpl;

import com.hengxin.constant.HengXinBusinessEnum;
import com.hengxin.module.contract.entity.ContractProduct;
import com.hengxin.module.contract.entity.Product;
import com.hengxin.module.contract.repository.ContractProductRepository;
import com.hengxin.module.contract.repository.ProductRepository;
import com.hengxin.module.contract.service.ContractProductService;

/**<p>名称：ContractProductServiceImpl.java</p>
 * <p>描述：</p>
 * <pre>
 *    
 * </pre>
 * @author 鲍建明
 * @date 2014-11-4 下午9:41:24
 * @version 1.0.0
 */
@Service
public class ContractProductServiceImpl extends BaseServiceImpl<ContractProduct, Long> implements ContractProductService{

	@Autowired
	private ProductRepository productRepository;
	
	@Autowired
	private ContractProductRepository contractProductRepository;
	
	
	/* (non-Javadoc)
	 * @see com.hengxin.module.contract.service.ContractProductService#save(java.lang.Long, java.util.List)
	 */
	@Override
	public BigDecimal save(Long contractId, List<Product> products) throws BusinessException {
		BigDecimal totle = new BigDecimal(0);
		if(CollectionUtils.isNotEmpty(products)){
			for (Product product : products) {
				Product old = productRepository.findOne(product.getId());
				if(old == null){
					throw new BusinessException(HengXinBusinessEnum.RECORD_NOT_FIND);
				}
				totle = totle.add(multiply(old.getSalePrice(), product.getStockNum()));
				ContractProduct contractProduct = new ContractProduct();
				contractProduct.setContractId(contractId);
				contractProduct.setProductId(old.getId());
				contractProduct.setStockNum(product.getStockNum());
				super.save(contractProduct);
			}
		}
		return totle;
	}


	private BigDecimal multiply(BigDecimal yuan, int shu){
		if(yuan == null){
			return new BigDecimal(0);
		}
		return yuan.multiply(new BigDecimal(shu));
	}


	/* (non-Javadoc)
	 * @see com.hengxin.module.contract.service.ContractProductService#findByContractId(java.lang.Long)
	 */
	@Override
	public List<Map<String, Object>> findByContractId(Long contractId) {
		return contractProductRepository.findByContractId(contractId);
	}


	/* (non-Javadoc)
	 * @see com.hengxin.module.contract.service.ContractProductService#deleteByContractId(java.lang.Long)
	 */
	@Override
	public void deleteByContractId(Long contractId) {
		contractProductRepository.deleteByContractId(contractId);
	}
	
}
